package com.tonyodev.fetch2core;

import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;

import org.jetbrains.annotations.NotNull;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * The default Storage Resolver used by Fetch. Extend this class if you want to provide your
 * own implementation.
 *
 * @since 2021-05-20
 */
public class DefaultStorageResolver implements StorageResolver {
    @NotNull
    private final Context context;
    @NotNull
    private final String defaultTempDir;

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param defaultTempDir 默认临时路径
     */
    public DefaultStorageResolver(@NotNull Context context, @NotNull String defaultTempDir) {
        this.context = context;
        this.defaultTempDir = defaultTempDir;
    }

    @NotNull
    protected final Context getContext() {
        return this.context;
    }

    @NotNull
    protected final String getDefaultTempDir() {
        return this.defaultTempDir;
    }

    @Override
    public String createFile(String file, boolean increment) throws IOException, DataAbilityRemoteException {
        return StorageResolverHelper.createFileAtPath(file, increment, getContext());
    }

    @Override
    public boolean preAllocateFile(String file, long contentLength) throws IOException, DataAbilityRemoteException {
        if (file.isEmpty()) {
            throw new FileNotFoundException(file + " " + FetchErrorStrings.FILE_NOT_FOUND);
        }
        if (contentLength < 1) {
            return true;
        }
        StorageResolverHelper.allocateFile(file, contentLength, context);
        return true;
    }

    @Override
    public boolean deleteFile(String file) throws DataAbilityRemoteException {
        return StorageResolverHelper.deleteFile(file, getContext());
    }

    @Override
    public OutputResourceWrapper getRequestOutputResourceWrapper(Downloader.ServerRequest request) throws IOException, DataAbilityRemoteException {
        return StorageResolverHelper.getOutputResourceWrapper(request.getFile(), getContext());
    }

    @Override
    public String getDirectoryForFileDownloaderTypeParallel(Downloader.ServerRequest request) {
        return getDefaultTempDir();
    }

    @Override
    public boolean fileExists(String file) {
        if (file.isEmpty()) {
            return false;
        }
        try {
            OutputResourceWrapper outputResourceWrapper = StorageResolverHelper.getOutputResourceWrapper(file, getContext());
            outputResourceWrapper.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean renameFile(String oldFile, String newFile) throws DataAbilityRemoteException {
        if (oldFile.isEmpty() || newFile.isEmpty()) {
            return false;
        }
        return StorageResolverHelper.renameFile(oldFile, newFile, context);
    }
}
